package com.tbit.uqbike.webmanager.controller;

import com.tbit.uqbike.annos.OperateLog;
import com.tbit.uqbike.constant.HttpStatus;
import com.tbit.uqbike.constant.UserConstant;
import com.tbit.common.constant.MethodEnum;
import com.tbit.common.constant.ModuleEnum;
import com.tbit.uqbike.enums.SystemCodeEnum;
import com.tbit.uqbike.manager.exception.BaseException;
import com.tbit.uqbike.object.pojo.Machine;
import com.tbit.uqbike.object.pojo.MachineBorrow;
import com.tbit.uqbike.object.pojo.User;
import com.tbit.uqbike.object.pojo.dto.FinishOrderDTO;
import com.tbit.uqbike.object.value.LoginInfo;
import com.tbit.uqbike.object.view.JsonResult;
import com.tbit.common.entity.view.Result;
import com.tbit.uqbike.service.base.MachineService;
import com.tbit.uqbike.service.business.AccountService;
import com.tbit.uqbike.service.business.RideLogDetailsService;
import com.tbit.uqbike.service.business.UserService;
import com.tbit.uqbike.service.rpcservice.MachineBorrowService;
import com.tbit.uqbike.webmanager.util.Assert;
import com.tbit.uqbike.webmanager.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;

/**
 * 当前借用车辆
 *
 * @author Leon
 * 2017年2月24日 下午5:51:05
 */
@Validated
@RestController
@RequestMapping(value = "/machineBorrow", produces = BaseController.MEDIA_JSON_UTF8)
public class MachineBorrowController extends BaseController {
    @Autowired
    private MachineBorrowService machineBorrowService;
    @Autowired
    private UserService userService;
    @Autowired
    private MachineService machineService;
    @Autowired
    private AccountService accountService;
    @Autowired
    private RideLogDetailsService rideLogDetailsService;

    /* 手动结束订单 (弃用) */
    @RequestMapping("/finishOrder")
    @OperateLog(module = ModuleEnum.ORDER, methods = MethodEnum.ORDER_FINISH)
    public JsonResult finishOrder(Integer accountId, String phone, String machineNO,
                                  @NotNull(message = "ver.secret.notNull") String secret,
                                  @NotNull(message = "ver.money.notNull") Integer money,
                                  @NotNull(message = "ver.remark.notNull") String remark, HttpServletRequest request) {
        Integer userId = null;
        if (StringUtils.isNotEmpty(phone)) {
            Integer brandId = accountService.getBrandId(accountId);
            User user = userService.getByAccountPhone(brandId, phone);
            userId = user == null ? null : user.getUserId();
        }
        if (userId == null) {
            Machine machine = machineService.getByMachineNO(machineNO);
            userId = machine == null ? null : machine.getLastUserId();
        }

        //调用新接口，防止前端缓存还在，调用了旧接口产生脏数据
        FinishOrderDTO finishOrderDTO = new FinishOrderDTO();
        finishOrderDTO.setUserId(userId);
        finishOrderDTO.setMoney(money.longValue());
        finishOrderDTO.setPsw(secret);
        finishOrderDTO.setRemark(remark);
        Result result = rideLogDetailsService.finishOrder(BaseController.getLogin(request), finishOrderDTO);
        if (HttpStatus.SUCCESS == result.getCode()) {
            return JsonResult.ok();
        } else {
            throw new BaseException(result.getMsg());
        }
        /*LoginInfo loginInfo = getLogin(request);
        Assert.notNull(accountId, "ver.accountId.notNull");
        if (phone == null && machineNO == null) {
            throw new BaseException(SystemCodeEnum.PHONE_MACHINENO_CHOICE_ONE);
        }

        *//**密码校验*//*
        if (!OperaPswConstant.ORDER_FINISH_MANUAL.equals(secret)) {
            throw new BaseException(SystemCodeEnum.SECRET_ERROR);
        }
        machineBorrowService.finishRideOrder(loginInfo, accountId, phone, machineNO, money, remark);

        return JsonResult.ok();*/
    }

    /**
     * 手动结束订单 (运维端调用) (弃用)
     */
    @RequestMapping("/finishOrderM")
    @OperateLog(module = ModuleEnum.ORDER, methods = MethodEnum.ORDER_FINISH)
    public JsonResult finishOrderM(String userCode,
                                   @NotNull(message = "ver.secret.notNull") String secret,
                                   @NotNull(message = "ver.money.notNull") Integer money,
                                   @NotNull(message = "ver.remark.notNull") String remark,
                                   Boolean deposit, HttpServletRequest request) {
        Machine machine = machineService.getByUserCode(userCode);
        Integer userId = machine == null ? null : machine.getLastUserId();
        //调用新接口，防止前端缓存还在，调用了旧接口产生脏数据
        FinishOrderDTO finishOrderDTO = new FinishOrderDTO();
        finishOrderDTO.setUserId(userId);
        finishOrderDTO.setMoney(money.longValue());
        finishOrderDTO.setPsw(secret);
        finishOrderDTO.setRemark(remark);
        Result result = rideLogDetailsService.finishOrder(BaseController.getLogin(request), finishOrderDTO);
        if (HttpStatus.SUCCESS == result.getCode()) {
            return JsonResult.ok();
        } else {
            throw new BaseException(result.getMsg());
        }
        /**秘钥校验*/
        /*if (!OperaPswConstant.ORDER_FINISH_MANUAL.equals(secret)) {
            throw new BaseException(SystemCodeEnum.SECRET_ERROR);
        }
        machineBorrowService.finishRideOrderM(userCode, money, remark);
        return JsonResult.ok();*/
    }


    /**
     * 查询用户借用的车辆
     */
    @RequestMapping("/getBorrowBike")
    public JsonResult getBorrowBike(Integer accountId,
                                    @NotNull(message = "ver.phone.notNull") String phone,
                                    HttpServletRequest request) {
        // 获取用户信息
        LoginInfo loginInfo = getLogin(request);
        List<Machine> machines = new ArrayList<>();
        if (loginInfo.type.equals(UserConstant.USER_ADMIN)) {
            Assert.notNull(accountId, "ver.accountId.notNull");
        } else if (loginInfo.type.equals(UserConstant.USER_BRAND)) {
            accountId = loginInfo.id;
        } else {
            accountId = accountService.getBrandId(loginInfo.id);
        }

        List<User> users = userService.getByAccountIdAndPhone(accountId, phone);
        if (users == null || users.size() < 1) {
            throw new BaseException(SystemCodeEnum.USER_NOT_EXIT);
        }

        MachineBorrow machineBorrow = machineBorrowService.getByUserId(users.get(0).getUserId());
        if (machineBorrow != null) {
            Machine machine = machineService.getByMachineId(machineBorrow.getMachineId());
            if (machine != null) {
                List<Integer> accountIds = accountService.getAllOperateAccountId(loginInfo);
                if (accountIds.contains(machine.getAccountId())) {
                    machines.add(machine);
                }
            }
        }

        return JsonResult.ok(machines);
    }


    @RequestMapping("/order")
    public void finishOrderM() {
        machineBorrowService.order();
    }

    ;

}